﻿using DataLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Common;
using LinqKit;

namespace TicketSystem
{
    public partial class Form_Search : Form
    {
        public Form_Search()
        {
            InitializeComponent();
        }
        private TicketSystemEntities tse = new TicketSystemEntities();

        private System.Data.DataTable SalesTable(IQueryable<Sales> result)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("流水号"); dt.Columns.Add("旅行社"); dt.Columns.Add("导游姓名"); dt.Columns.Add("导游卡号"); dt.Columns.Add("一道船数量"); dt.Columns.Add("公园票数量"); 
            dt.Columns.Add("公园学生票数量"); dt.Columns.Add("颐内一道船"); dt.Columns.Add("颐内二道船"); dt.Columns.Add("签单人数"); dt.Columns.Add("签单号"); 
            dt.Columns.Add("签单金额"); dt.Columns.Add("付款金额"); dt.Columns.Add("总金额"); dt.Columns.Add("开票时间"); dt.Columns.Add("票号"); dt.Columns.Add("操作员");
            var listSales = (from n in result
                             select new
                             {
                                 n.SaleID,
                                 n.SaleGuid,
                                 n.DepartmentsGuides.Departments.DepartmentName,
                                 n.DepartmentsGuides.Guides.Name,
                                 n.DepartmentsGuides.Guides.GuideCard,
                                 n.TicketOne,
                                 n.TicketPark,
                                 n.TicketParkSpecial,
                                 n.TicketTwo,
                                 n.TicketThree,
                                 n.SignedPeople,
                                 n.SignedNumber,
                                 n.SignedMoney,
                                 n.PurchaseMoney,
                                 n.Created_at,
                                 n.OperatorID
                             }).ToList();

            for (int i = 0; i < listSales.Count(); i++)
            {
                List<string> list = new List<string>();
                list.Add(listSales[i].SaleID.ToString());                
                list.Add(listSales[i].DepartmentName.ToString());
                list.Add(listSales[i].Name.ToString());
                list.Add(listSales[i].GuideCard.ToString());
                list.Add(listSales[i].TicketOne.ToString());
                list.Add(listSales[i].TicketPark.ToString());
                list.Add(listSales[i].TicketParkSpecial.ToString());
                list.Add(listSales[i].TicketTwo.ToString());
                list.Add(listSales[i].TicketThree.ToString());
                list.Add(listSales[i].SignedPeople.ToString());
                list.Add(listSales[i].SignedNumber.ToString());
                list.Add(listSales[i].SignedMoney.ToString());
                list.Add(listSales[i].PurchaseMoney.ToString());
                list.Add((decimal.Parse(listSales[i].SignedMoney.ToString()) + decimal.Parse(listSales[i].PurchaseMoney.ToString())).ToString());
                list.Add(listSales[i].Created_at.ToString());
                list.Add(listSales[i].SaleGuid.ToString());
                list.Add(tse.Operators.Find(listSales[i].OperatorID).Name);
                dt.Rows.Add(list.ToArray());
            }
            return dt;
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (cBox_OutOrBack.Text == "出票单据")
            {
                int row = e.RowIndex;
                int saleid = int.Parse(dataGridView1[0, row].Value.ToString());
                DialogResult dresult = MessageBox.Show("是否打印流水号为" + saleid + "的票据", "打印票据", MessageBoxButtons.OKCancel);
                if (dresult == DialogResult.OK)
                {
                    List<String> list = Common.PrintDataGridView.GetLocalPrinters(); //获得系统中的打印机列表
                    foreach (String s in list)
                    {
                        if (s.ToUpper().Contains("EPSON"))
                        {
                            Common.Externs.SetDefaultPrinter(s);
                            break;
                        }
                    }
                    Print_Doc(saleid);
                }
            }
        }

        private void Print_Doc(int saleid)
        {
            var sale = tse.Sales.Find(saleid);
            string operatorname = tse.Operators.Find(sale.OperatorID).Name;
            PrintDoc pd = new PrintDoc();
            System.Drawing.Image _img = pd.CreateQuickMark(sale.SaleGuid.ToString());
            if (sale.TicketOne > 0)
            {
                this.printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                //这里打印的首道船就不能区分出学生和成人了;
                pd = print("一道船", "万寿寺", _img, sale.SaleID.ToString(), sale.DepartmentsGuides.Departments.DepartmentName, sale.DepartmentsGuides.Guides.Name, sale.TicketOne, sale.TicketOne, 0, operatorname);
                this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                printPreviewDialog1.Document = printDocument1; //将写好的格式给打印预览控件以便预览               
            }
            if (sale.TicketPark > 0 || sale.TicketParkSpecial > 0)
            {
                this.printDocument2.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                pd = print("进园票", "万寿寺", _img, sale.SaleID.ToString(), sale.DepartmentsGuides.Departments.DepartmentName, sale.DepartmentsGuides.Guides.Name, sale.TicketPark + sale.TicketParkSpecial, sale.TicketPark, sale.TicketParkSpecial, operatorname);
                this.printDocument2.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                printPreviewDialog2.Document = printDocument2; //将写好的格式给打印预览控件以便预览  
            }
            if (sale.TicketTwo > 0)
            {
                this.printDocument3.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                pd = print("二道船", "颐和园", _img, "", sale.DepartmentsGuides.Departments.DepartmentName, sale.DepartmentsGuides.Guides.Name, sale.TicketTwo, sale.TicketTwo, 0, operatorname);
                this.printDocument3.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                printPreviewDialog3.Document = printDocument3; //将写好的格式给打印预览控件以便预览  
            }
            if (sale.TicketThree > 0)
            {
                this.printDocument4.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("复写", 950, 367);
                pd = print("3道船", "颐和园", _img, "", sale.DepartmentsGuides.Departments.DepartmentName, sale.DepartmentsGuides.Guides.Name, sale.TicketThree, sale.TicketThree, 0, operatorname);
                this.printDocument4.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd.MyPrintDocument);
                printPreviewDialog4.Document = printDocument4; //将写好的格式给打印预览控件以便预览  
            }
            MessageBoxButtons mb = MessageBoxButtons.YesNo;
            DialogResult dr = MessageBox.Show(DateTime.Now + "，是否预览打印效果?", "立即打印", mb);
            if (dr == DialogResult.Yes)
            {
                if (printPreviewDialog1.Document != null)
                {
                    DialogResult result1 = printPreviewDialog1.ShowDialog();
                }
                if (printPreviewDialog2.Document != null)
                {
                    DialogResult result2 = printPreviewDialog2.ShowDialog();
                }
                if (printPreviewDialog3.Document != null)
                {
                    DialogResult result3 = printPreviewDialog3.ShowDialog();
                }
                if (printPreviewDialog1.Document != null)
                {
                    DialogResult result4 = printPreviewDialog4.ShowDialog();
                }
            }
            else
            {
                if (printPreviewDialog1.Document != null && (sale.TicketOne > 0))
                {
                    printDocument1.Print();
                }
                if (printPreviewDialog2.Document != null && (sale.TicketPark > 0 || sale.TicketParkSpecial > 0))
                {
                    printDocument2.Print();
                }
                if (printPreviewDialog3.Document != null && (sale.TicketTwo > 0))
                {
                    printDocument3.Print();
                }
                if (printPreviewDialog4.Document != null && (sale.TicketThree > 0))
                {
                    printDocument4.Print();
                }
            }
        }
        private System.Data.DataTable BacksTable(IQueryable<Backs> result)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            dt.Columns.Add("ID"); dt.Columns.Add("原始流水号"); dt.Columns.Add("旅行社"); dt.Columns.Add("导游姓名");
            dt.Columns.Add("导游卡号"); dt.Columns.Add("一道船数量"); dt.Columns.Add("二道船数量"); dt.Columns.Add("三道船数量");
            dt.Columns.Add("公园票数量"); dt.Columns.Add("公园学生票数量"); dt.Columns.Add("退票金额"); dt.Columns.Add("退票时间");
            dt.Columns.Add("原始票号"); dt.Columns.Add("操作员");
            var listBacks = (from n in result
                             select new
                             {
                                 n.BackID,
                                 n.SaleID,
                                 n.Sales.DepartmentsGuides.Departments.DepartmentName,
                                 n.Sales.DepartmentsGuides.Guides.Name,
                                 n.Sales.DepartmentsGuides.Guides.GuideCard,
                                 n.BackOne,
                                 n.BackPark,
                                 n.BackParkSpecial,
                                 n.BackTwo,
                                 n.BackThree,
                                 n.BackMoney,
                                 n.Created_at,
                                 n.Sales.SaleGuid,
                                 n.OperatorID
                             }).ToList();

            for (int i = 0; i < listBacks.Count(); i++)
            {
                List<string> list = new List<string>();
                list.Add(listBacks[i].BackID.ToString());
                list.Add(listBacks[i].SaleID.ToString());
                list.Add(listBacks[i].DepartmentName);
                list.Add(listBacks[i].Name.ToString());
                list.Add(listBacks[i].GuideCard.ToString());
                list.Add(listBacks[i].BackOne.ToString());
                list.Add(listBacks[i].BackPark.ToString());
                list.Add(listBacks[i].BackParkSpecial.ToString());
                list.Add(listBacks[i].BackTwo.ToString());
                list.Add(listBacks[i].BackThree.ToString());
                list.Add(listBacks[i].BackMoney.ToString());
                list.Add(listBacks[i].Created_at.ToString());
                list.Add(listBacks[i].SaleGuid.ToString());
                list.Add(tse.Operators.Find(listBacks[i].OperatorID).Name);
                dt.Rows.Add(list.ToArray());
            }
            return dt;
        }
        private void btn_Search_Click(object sender, EventArgs e)
        {
            var _where = PredicateBuilder.New<Sales>(true);
            var _whereBack = PredicateBuilder.New<Backs>(true);            
            if (!string.IsNullOrEmpty(txt_SaleInfo.Text))
            {
                if (txt_SaleInfo.Text.Contains("-"))
                {
                    try
                    {
                        Guid guid = Guid.Parse(txt_SaleInfo.Text);
                        _where = _where.And(u => u.SaleGuid == guid);
                        _whereBack = _whereBack.And(u => u.BackNumber == txt_SaleInfo.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("格式不合法:" + ex.Message);
                        return;
                    }
                }
                else
                {
                    try
                    {
                        int saleid = int.Parse(txt_SaleInfo.Text);
                        _where = _where.And(u => u.SaleID == saleid);
                        _whereBack = _whereBack.And(u => u.SaleID == saleid);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("格式不合法:" + ex.Message);
                        return;
                    }
                }
            }
            if (!string.IsNullOrEmpty(txt_GuideInfo.Text))
            {
                int a = 0;
                if (int.TryParse(txt_GuideInfo.Text, out a) == false)
                {
                    _where = _where.And(u => u.DepartmentsGuides.Guides.Name.Trim() == txt_GuideInfo.Text.Trim());
                    _whereBack = _whereBack.And(u => u.Sales.DepartmentsGuides.Guides.Name.Trim() == txt_SaleInfo.Text.Trim());
                }
                else
                {
                    _where = _where.And(u => u.DepartmentsGuides.Guides.GuideCard.Trim() == txt_GuideInfo.Text.Trim());
                    _whereBack = _whereBack.And(u => u.Sales.DepartmentsGuides.Guides.GuideCard.Trim() == txt_GuideInfo.Text.Trim());
                }
            }
            if (!string.IsNullOrEmpty(txt_Operator.Text))
            {
                var _ope = tse.Operators.Where(u => u.Name == txt_Operator.Text);
                if (_ope.Count() == 1)
                {
                    int id = _ope.First().OperatorID;
                    _where = _where.And(u => u.OperatorID == id);
                    _whereBack = _whereBack.And(u => u.OperatorID == id);
                }
                else
                {
                    MessageBox.Show("操作员不存在");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(txt_TravelName.Text))
            {
                _where = _where.And(u => u.DepartmentsGuides.Departments.DepartmentName == txt_TravelName.Text);
                _whereBack = _whereBack.And(u => u.Sales.DepartmentsGuides.Departments.DepartmentName == txt_TravelName.Text);
            }
            if (checkBox_DateSpan.Checked)
            {
                DateTime start = DateTime.Parse(dateTimePicker_Start.Text);
                DateTime end = DateTime.Parse(dateTimePicker_End.Text);
                _where = _where.And(u => u.Created_at > start && u.Created_at < end);
                _whereBack = _whereBack.And(u => u.Created_at > start && u.Created_at < end);
            }
            if (cBox_OutOrBack.Text == "出票单据")
            {
                var result = (IQueryable<Sales>)tse.Sales;
                if (!string.IsNullOrEmpty(cBox_TicketType.Text))
                {
                    switch (cBox_TicketType.Text)
                    {
                        case "全部":
                            break;
                        case "签单":
                            _where = _where.And(u => u.SignedMoney > 0);
                            break;
                        case "非签单":
                            _where = _where.And(u => u.PurchaseMoney > 0 && u.SignedMoney == 0);
                            break;
                        default:
                            break;
                    }
                }
                if (checkBox1.Checked)
                {
                    result = tse.Sales.AsExpandable().Where(_where).Take(50);
                }
                else
                {
                    result = tse.Sales.AsExpandable().Where(_where);
                }
                try
                {
                    dataGridView1.DataSource = SalesTable(result);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
                }
            }
            else
            {
                var result = (IQueryable<Backs>)tse.Backs;
                result = tse.Backs.AsExpandable().Where(_whereBack);
                try 
                {
                    dataGridView1.DataSource = BacksTable(result);
                }
                 catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
                }
            }
            txt_GuideInfo.Text = txt_GuideInfo.Text.Trim();
            txt_SaleInfo.Text = txt_SaleInfo.Text.Trim();
            txt_Operator.Text = txt_Operator.Text.Trim();
            txt_TravelName.Text = txt_TravelName.Text.Trim();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox_DateSpan.Checked)
            {
                dateTimePicker_Start.Enabled = true;
                dateTimePicker_End.Enabled = true;
            }
            else
            {
                dateTimePicker_Start.Enabled = false;
                dateTimePicker_End.Enabled = false;
            }
        }

        //回车事件（下一个）
        private void PressEnter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                System.Windows.Forms.SendKeys.Send("{TAB}");
            }
        }

        private void PressEnter2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.btn_Search_Click(sender, e);
            }
        }

        private void Form_Search_Load(object sender, EventArgs e)
        {
            cBox_OutOrBack.Text = "出票单据";
        }
        private PrintDoc print(string TicketType, string wharf, System.Drawing.Image img, string saleID, string departmentName, string guide, int people1, int people2, int people3, string operatorName)
        {
            PrintDoc pd = new PrintDoc();
            System.Collections.Hashtable ht = new System.Collections.Hashtable();
            ht.Add("凭证", TicketType);
            ht.Add("码头", wharf);
            ht.Add("二维码", img);
            ht.Add("票号", saleID);
            ht.Add("社名", departmentName);
            ht.Add("导游", guide);
            ht.Add("进园", people1);
            ht.Add("成人", people2);
            ht.Add("学生", people3);
            ht.Add("开票人", operatorName);
            pd.PrintHash = new System.Collections.Hashtable();
            pd.PrintHash = ht;
            return pd;
        }

        private void cBox_OutOrBack_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cBox_OutOrBack.Text == "退票单据")
                cBox_TicketType.Enabled = false;
            else
                cBox_TicketType.Enabled = true;
        }

        private void checkBox1_CheckedChanged_1(object sender, EventArgs e)
        {

        }
       
    }
}
